/**
  * 网络公共类
  * by dily
  * (c) copyright 2014 - 2035
  * All Rights Reserved. 
  * 存放网络公共方法 
  * 注意：是异步请求
  */
module Network {

    export var netArr: Array<any> = [];

    /** 
     * GET请求 
     * @param url
     * @param callback
     */
    export function get(url: string, callback = function () { }): void {
        this.sendInfo(url, "", callback, egret.URLRequestMethod.GET);
    }

    /**
     * POST请求
     * @param url
     * @param param
     * @param callback
     */
    export function post(url: string, param: any = {}, callback = function () { }): void {
        let paramStr = turnParam(param);
        this.sendInfo(url, paramStr, callback, egret.URLRequestMethod.POST);
    }

    //发送消息
    export function sendInfo(url: string = "", urlData: any = "", callback = function () { }, str: string = egret.URLRequestMethod.POST): void {
        this.netArr.push({ "key": url + urlData, "fun": callback });
        var loader: egret.URLLoader = new egret.URLLoader();
        loader.dataFormat = egret.URLLoaderDataFormat.TEXT;
        loader.addEventListener(egret.Event.COMPLETE, this.onGetComplete, this);
        // loader.addEventListener(egret.IOErrorEvent.IO_ERROR,this.onGetComplete,this);
        var request: egret.URLRequest = new egret.URLRequest(url);
        request.method = str;
        request.data = new egret.URLVariables(urlData);
        loader.load(request);
    }

    export function turnParam(data): string {
        var param = "";
        for (var key in data) {
            if (data.hasOwnProperty(key)) {
                var element = data[key];
                param += key + "=" + element + "&";
            }
        }
        return param.substr(0, param.length - 1);
    }

    //GET请求完成
    //发送消息 消息为 网址名称
    export function onGetComplete(event: egret.Event): void {
        var loader: egret.URLLoader = <egret.URLLoader>event.target;
        loader.dataFormat = egret.URLLoaderDataFormat.TEXT;
        var data: egret.URLVariables = loader.data;

        var notify: string = loader._request.url;
        var variables: string = "";
        if (loader._request.data.variables) {
            variables = this.turnParam(loader._request.data.variables);
        }
        var len = this.netArr.length;
        for (var i = 0; i < this.netArr.length; i++) {
            if (this.netArr[i].key == notify + variables) {
                this.netArr[i].fun.apply(null, [data]);
                this.netArr.splice(i, 1);
                break;
            }
        }
    }
}



